package com.raising.framework.shiro;

import com.raising.utils.EncodesUtils;
import com.raising.utils.JStringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 判断用户有没有登录
 * @author GaoYuan
 * @date 2018/11/13 上午11:10
 */
public class MyUserFilter extends UserFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyUserFilter.class);

    /** 判断用户有没有登录 */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(logger.isDebugEnabled()){
            logger.debug("【Shiro】>>> MyUserFilter.isAccessAllowed()，判断用户是否登录");
        }
        // 如果是登录请求，也就是不拦截登录路径(登录没有配这个filter的话，此判断是没有意义的)
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            // 缓存获取当前登录对象，如果获取不到，说明没有登录
            Subject subject = getSubject(request, response);
            if(subject.getPrincipal() == null){
                // session失效
                return false;
            }
            return true;
        }
    }

    /**
     * 如果用户没有登录进入此方法
     * @author GaoYuan
     * @date 2018/11/13 上午11:11
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if(logger.isDebugEnabled()){
            logger.debug("【Shiro】>>> MyUserFilter.onAccessDenied()，用户尚未登录");
        }
        HttpServletRequest re = (HttpServletRequest)request;
        String query = re.getQueryString();
        StringBuffer oldUrl = re.getRequestURL();
        if(JStringUtils.isNotBlank(query)){
            oldUrl = oldUrl.append("?").append(query);
        }
        String jumpUrl = EncodesUtils.urlEncode(oldUrl.toString());

        saveRequest(request);
        String loginUrl = getLoginUrl();
        if(JStringUtils.isNotBlank(jumpUrl)){
            loginUrl = loginUrl + (loginUrl.contains("?") ? "&" : "?") + "jumpUrl="+jumpUrl;
        }
        WebUtils.issueRedirect(request, response, loginUrl);
        return false;
    }

}
